<?php

namespace app\admin\controller;


use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\Db;
use think\Validate;

class Major extends Base
{
        public function index(){
            extract(input());
            $where = [];
            if(isset($major_name) && !empty($major_name)){
                $where['major_name'] = ['like','%'.$major_name.'%'];
            }
            if(isset($school_id) && !empty($school_id)){
                $where['school_id'] = $school_id;
            }
            if(isset($school_name) && !empty($school_name)){
                $where['school_name'] = ['like','%'.$school_name.'%'];
            }
            $data = Db::name('tp_major')
                ->alias('m')
                ->join('tp_school s','m.school_id=s.id')
                ->field('m.id,major_name,s.school_name')
                ->order('m.id DESC')
                ->where($where)
                ->paginate('5',false,['query'=>input()]);
            $page = $data->render();
            $school = Db::name('tp_school')->select();
            $this->assign('school',$school);
            $this->assign('data',$data);
            $this->assign('page',$page);
            return $this->fetch('major');
        }
        public function add(){
            $data = Db::name('tp_school')->select();
            $this->assign('data',$data);
            return $this->fetch();
        }
        public function addPost(){
            $data = input();
            $res = Db::name('tp_major')->insert($data);
            if($res){
                $this->success('添加成功');
            }else{
                $this->error('添加失败');
            }
        }
        public function edit(){

            $id  = input('id');
            $user =Db::name('tp_major')
                ->where('id',$id)
                ->find();
            $data = Db::name('tp_school')->select();
            $this->assign('data',$data);
            $this->assign('user',$user);
            $this->assign('id',$id);
            return $this->fetch();
        }
        public function editPost(){
            $data = input();
            $rule = [
                'major_name'  => 'require',
            ];
            $msg = [
                'major_name.require' => '专业名称不能为空',
            ];
            $validate = new Validate($rule, $msg);
            $result   = $validate->check($data);
            if (true!==$result){
                $this->error($validate->getError());
            }
            $edit = Db::name('tp_major')
                ->where('id',$data['id'])->update($data);
            if($edit){
                $this->success('修改成功','school/school');
            }else{
                $this->error('修改失败');
            }
        }
        public function del(){
            $data = input('id');
            $del = Db::name('tp_major')->delete($data);
            if($del==1){
                $this->success('删除成功','major/index');
            }else{
                $this->error('删除失败');
            }
        }
        public function batchDelete(){
            $ids = input('ids/a');
            //print_r($ids);die;
            $del = Db::name('tp_major')->delete($ids);
            if($del){
                $this->success('删除成功','major/index');
            }else{
                $this->error('删除失败');
            }
        }
    public function exportExcel()
    {
        // 查询要导出的数据
        $data = Db::name('tp_major')
            ->join('tp_school','tp_major.school_id=tp_school.id')
            ->select();

        // 实例化
        $spreadsheet = new Spreadsheet();
        // 获取活动工作薄
        $sheet = $spreadsheet->getActiveSheet();

        // 获取单元格
        $cellA = $sheet->getCell('A1');
        // 设置单元格的值
        $cellA->setValue('ID');
        // 设置 A 列 列宽
        $sheet->getColumnDimension('A')->setWidth(10);
        // 设置第一行 行高
        $sheet->getRowDimension(1)->setRowHeight(20);

        $cellB = $sheet->getCell('B1');
        $cellB->setValue('专业名称');
        $sheet->getColumnDimension('B')->setWidth(30);

        $cellC = $sheet->getCell('C1');
        $cellC->setValue('所在学校');
        $sheet->getColumnDimension('C')->setWidth(40);

        // 设置样式 标题栏
        $styleArray = [
            'alignment' => [
                'horizontal' => 'center', //水平居中
                'vertical' => 'center', //垂直居中
            ],
            'font' => [
                'name' => '黑体',
                'bold' => false,
                'size' => 10
            ]
        ];
        // 设置样式 正文
        $styleArrayBody = [
            'alignment' => [
                'horizontal' => 'center', //水平居中
                'vertical' => 'center', //垂直居中
            ],
            'font' => [
                'name' => '宋体',
                'bold' => false,
                'size' => 10
            ]
        ];
        // 应用样式
        $sheet->getStyle('A1')->applyFromArray($styleArray);
        $sheet->getStyle('B1')->applyFromArray($styleArray);
        $sheet->getStyle('C1')->applyFromArray($styleArray);


        // 从 A2 开始填充数据
        foreach ($data as $k => $v) {
            $n = $k + 2;
            // 获取单元格
            $cellA = $sheet->getCell('A'.$n);
            // 设置单元格的值
            $cellA->setValue($v['id']);

            $cellB = $sheet->getCell('B'.$n);
            $cellB->setValue($v['major_name']);

            $cellC = $sheet->getCell('C'.$n);
            $cellC->setValue($v['school_name']);


            // 再给表格体设置样式
            $sheet->getStyle('A'.$n)->applyFromArray($styleArrayBody);
            $sheet->getStyle('B'.$n)->applyFromArray($styleArrayBody);
            $sheet->getStyle('C'.$n)->applyFromArray($styleArrayBody);

        }

        // 下载文件名
        $filename = '专业列表.xlsx';
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename='.$filename);
        header('Cache-Control: max-age=0');

        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
    }
    //导入
    public function Excel_export()
    {
        // 接收文件
        $file = $_FILES['file']['tmp_name'];
        // 创建读操作
        $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
        // 打开文件、载入excel表格
        $spreadsheet = $reader->load($file);
        // 获取活动工作薄
        $sheet = $spreadsheet->getActiveSheet();


        // 获取总行数
        $highestRow = $sheet->getHighestRow();

        // 存放插入成功的记录
        $successLog = [];
        // 存放插入失败的记录
        $failLog = [];

        // 从第二行开始读取表格数据，循环写入数据库
        for ($i = 2; $i <= $highestRow; $i++) {
            // 第 1 次循环获取第 2列 第 2 行单元格的值，第 2 次循环获取第 3 列 第 3 行单元格的值
            $major_name = $sheet->getCellByColumnAndRow(2, $i)->getValue();
            $school_id = $sheet->getCellByColumnAndRow(3, $i)->getValue();
            // 假设数据表有以下字段

            $data = [
                'major_name' => $major_name,
                'school_id' => $school_id,
            ];
            $insert = Db::name('tp_major')->insert($data);
            if ($insert) {
                $successLog[] = '第' . $i . '条，插入成功';
            } else {
                $failLog[] = '第' . $i . '条，插入失败';
            }
        }
        // 将成功数和失败数返回给 ajax
        return json(['success' => count($successLog), 'fail' => count($failLog)]);
    }
}